package com.mgg.payment.controller.pay;

import com.mgg.common.dto.OrderDTO;
import com.mgg.common.enums.OrderPayWayEnum;
import com.mgg.common.enums.OrderStatusEnum;
import com.mgg.common.util.ResultVOUtil;
import com.mgg.payment.enums.PaymentResultEnum;
import com.mgg.payment.service.account.AccountService;
import com.mgg.payment.service.order.SalesOrderService;
import com.mgg.payment.service.pay.PaymentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class PaymentController {

	private Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
    private PaymentService paymentService;

	@Autowired
    private SalesOrderService orderService;

	@Autowired
    private AccountService accountService;

	/**
	 * 支付
	 */
	@GetMapping(value = "/create")
	public Object pay(@RequestParam("orderId") String orderId) {
		OrderDTO order = orderService.getOrderByOrderId(orderId);
		if (order == null) {
			return ResultVOUtil.error(PaymentResultEnum.ORDER_NOT_EXIST);
		}
		if(OrderStatusEnum.UN_PAY.getCode() != order.getStatus()) {
			return ResultVOUtil.error(PaymentResultEnum.ORDER_STATUS_ERROR);
		}
		paymentService.paySuccess(order, OrderPayWayEnum.ACOUNT.getCode(), null);
		return ResultVOUtil.success();
	}

    /**
     *
     */
    @GetMapping(value = "/order/rebate")
    public Object allocateOrderRebate(@RequestParam("order_id") String orderId, @RequestParam("super_id") String superId) {
        OrderDTO order = orderService.getOrderByOrderId(orderId);
        if (order == null) {
            return ResultVOUtil.error(PaymentResultEnum.ORDER_NOT_EXIST);
        }
        if(OrderStatusEnum.FINISH.getCode() != order.getStatus()) {
            return ResultVOUtil.error(PaymentResultEnum.ORDER_STATUS_ERROR);
        }

        Map<String,Integer> openGiftConfig = orderService.getOpenGiftConfigByOrderId(orderId);
        Integer orderType = openGiftConfig.get("order_type");
        accountService.sendRegistShopkeeperOrderRebate(order, order.getUserId(), orderType, 1);
        accountService.sendRegistShopkeeperOrderRebate(order, superId, orderType, 2);
        return ResultVOUtil.success();
    }
}
